﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using COMOSOFT.Main;
using DevExpress.XtraGrid.Views.Grid;
using COMOSOFT.Class;
using System.IO;

namespace COMOSOFT.MatarialManagement.Forms
{
    public partial class FrmAccessoriesView : Form
    {
        Task task;
        Image img;
        int year, flag = 1;
        string Distr;
        FrmMaterial FrmMA = null;
        FrmMain frmain = null;
        DataTable dbTemp = null;
        ClassShare cls = new ClassShare("FrmAccessoriesView");
        public FrmAccessoriesView(FrmMain _frmain)
        {
            InitializeComponent();
            this.frmain = _frmain;
        }
        #region [Load Data]
        public void LoadMAGV(int _year, string _Distr)
        {
            this.year = _year;
            this.Distr = _Distr;
            radioGroup_MAList.SelectedIndex = 0;
            radioGroup_MAList.Properties.Items[0].Description = "All Accessories " + this.year.ToString();
            CallMALibrary(year, Distr);
        }
        private void CallMALibrary(int year, string dis)
        {
            splashScreenManager1.ShowWaitForm();
            gridControl_MAGaneral.DataSource = null;
            task = Task.Factory.StartNew(() => LoadData(year, flag, dis));
            task.ContinueWith(tt => FillTable());
        }

        private delegate void dlgFillTable();
        private void FillTable()
        {
            if (InvokeRequired)
            {
                this.Invoke(new dlgFillTable(FillTable));
            }
            else
            {
                gridControl_MAGaneral.DataSource = dataSetMatarial.sp_MAGeneral;
                splashScreenManager1.CloseWaitForm();
            }
        }


        public void LoadData(int year, int flag, string dis)
        {
            try
            {
                sp_MAGeneralTableAdapter.Fill(this.dataSetMatarial.sp_MAGeneral, year, flag, dis);
                dbTemp = new DataTable();
                dbTemp.Columns.Add("ID");
                dbTemp.Columns.Add("Img", typeof(object));
                DataTable dbMA = dataSetMatarial.sp_MAGeneral;
                for (int i = 0; i < dbMA.Rows.Count; i++)
                {
                    DataRow newrow = dbTemp.NewRow();
                    if (dbMA.Rows[i]["Picture"].ToString() != "")
                    {
                        if (!File.Exists(ClassShare.lcMaterial + dbMA.Rows[i]["Picture"].ToString()))
                           cls.Dowload(ClassShare.ftpMaterial, ClassShare.lcMaterial, dbMA.Rows[i]["Picture"].ToString());
                        string path = ClassShare.lcMaterial + dbMA.Rows[i]["Picture"].ToString();
                        byte[] img = System.IO.File.ReadAllBytes(path);
                        newrow["Img"] = img;
                    }
                    else
                    {
                        if (!File.Exists(ClassShare.lcMaterial + "noImage.gif"))
                            cls.Dowload(ClassShare.ftpMaterial, ClassShare.lcMaterial, "noImage.gif");
                        string path = ClassShare.lcMaterial + "noImage.gif";
                        byte[] NoImg = System.IO.File.ReadAllBytes(path);
                        newrow["Img"] = NoImg;
                    }
                    newrow["ID"] = dbMA.Rows[i]["MADID"];
                    dbTemp.Rows.Add(newrow);
                }
            }
            catch
            {
                MessageBox.Show("Disconnection database! You can try later");
            }
        }
        #endregion

        #region [Select Radio]
        private void radioGroup_MAList_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (radioGroup_MAList.SelectedIndex == 0)
                {
                    flag = 1;
                }
                else
                {
                    flag = 0;
                }
                LoadData(year, flag, Distr);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion        
        #region [FromLoad]
        private void FrmAccessoriesView_Load(object sender, EventArgs e)
        {
            this.employeeTableAdapter.Fill(this.dataSetOrderManagement.Employee);
        }
        #endregion

        #region [DoubleClick Gridview]
        private void gridView_MAGeneral_DoubleClick(object sender, EventArgs e)
        {
            try
            {
                int MAID = Convert.ToInt32(gridView_MAGeneral.GetFocusedDataRow()["MAID"]);
                FrmMA = new FrmMaterial(MAID);
                //FrmMA.MdiParent = this.frmain;
                FrmMA.Show();
                FrmMA.LoadData();
                ClassShare.frMA = FrmMA;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion

        #region [Show Image]
        private Image LoadImg(string ID, int row)
        {
            try
            {
                if (dbTemp.Rows.Count > row && dbTemp.Rows[row]["ID"].ToString() == ID)
                {
                    using (System.IO.MemoryStream str = new System.IO.MemoryStream(dbTemp.Rows[row]["Img"] as byte[]))
                    {
                        img = Image.FromStream(str);
                        return img;
                    }
                }
            }
            catch
            {
                //ssageBox.Show(ex.Message);
            }
            return img;
        }
        private void gridView_MAGeneral_CustomUnboundColumnData(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDataEventArgs e)
        {
            try
            {
                DataRowView row = e.Row as DataRowView;
                GridView view = sender as GridView;
                if (e.Column.FieldName == "Image" && e.IsGetData && !view.IsGroupRow(e.ListSourceRowIndex))
                    e.Value = LoadImg(row["MADID"].ToString(), e.ListSourceRowIndex);
            }
            catch
            {
                //essageBox.Show(ex.Message);
            }
        }
        #endregion

        public void RefreshData()
        {
            sp_MAGeneralTableAdapter.Fill(this.dataSetMatarial.sp_MAGeneral, year, 1, Distr);
        }

        private void gridView_MAGeneral_ColumnFilterChanged(object sender, EventArgs e)
        {
            gridView_MAGeneral.OptionsBehavior.AutoExpandAllGroups = true;
        }       
    }
}
